package com.dns.reset.core;

import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Properties;

public class SSHCommandExecutor {
    private static final Logger logger = LoggerFactory.getLogger(SSHCommandExecutor.class);
    //远程主机的ip地址
    private String ip;
    //远程主机登录用户名
    private String username;
    //远程主机的登录密码
    private String password;
    //设置ssh连接的远程端口
    public static final int DEFAULT_SSH_PORT = 22;
    //保存输出内容的容器
    private ArrayList<String> stdout;

    /**
     * 初始化登录信息
     * @param ip
     * @param username
     * @param password
     */
    public SSHCommandExecutor(final String ip, final String username, final String password) {
        this.ip = ip;
        this.username = username;
        this.password = password;
        stdout = new ArrayList<String>();
    }
    /**
     * 执行shell命令
     * @param command
     * @return
     */
    public int execute(final String command) {
        int returnCode = 0;
        JSch jsch = new JSch();
        MyUserInfo userInfo = new MyUserInfo();
        Session session=null;
        ChannelExec channelExec=null;
        try {
            logger.info("开始连接服务器 IP:{},Port:{},userName:{},password:{}",ip,DEFAULT_SSH_PORT,username,password);
            //创建session并且打开连接，因为创建session之后要主动打开连接
            session = jsch.getSession(username, ip, DEFAULT_SSH_PORT);
            session.setPassword(password);
            session.setUserInfo(userInfo);
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            logger.info("创建session连接成功....");
            logger.info("打开通道，设置通道类型，和执行命令 {}",command);
            //打开通道，设置通道类型，和执行的命令
            Channel channel = session.openChannel("exec");
            channelExec = (ChannelExec)channel;
            channelExec.setCommand(command);

            channelExec.setInputStream(null);
            BufferedReader input = new BufferedReader(new InputStreamReader
                    (channelExec.getInputStream()));

            channelExec.connect();

            //接收远程服务器执行命令的结果
            StringBuilder result = new StringBuilder();
            String line= null;;
            while ((line = input.readLine()) != null) {
                result.append(line).append('\n');
                stdout.add(line);
            }
            input.close();
            logger.info("接收远程服务器执行命令的结果:{}" ,result.toString());
            // 得到returnCode
            if (channelExec.isClosed()) {
                returnCode = channelExec.getExitStatus();
            }



        } catch (JSchException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.info("执行命令时发生JSchException异常：{}",e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("执行命令时发生Exception异常：{}",e.getMessage());
        }finally {
            // 关闭通道
            channelExec.disconnect();
            //关闭session
            session.disconnect();
        }
        return returnCode;
    }
    /**
     * get stdout
     * @return
     */
    public ArrayList<String> getStandardOutput() {
        return stdout;
    }

    public static void main(final String [] args) {
        SSHCommandExecutor shell = new SSHCommandExecutor("xxx.xxx.xxx.xxx", "username", "password");
        shell.execute("uname -s -r -v");

        ArrayList<String> stdout = shell.getStandardOutput();
        for (String str : stdout) {
            System.out.println(str);
        }
    }
}
